package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo4_JUC {
    public static void main(String[] args) {
        Goods3 goods3 = new Goods3();


        new Thread(()->{
            //店家线程
            System.out.println("店家线程：");
            //增加多个商品
            for(int i = 0 ; i < 3 ; i++){
                goods3.addThisGoods();
            }
            System.out.println("店家新增好了！");
        },"restaurant").start();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程1：");
            goods3.buyThisGoods();
            System.out.println("顾客1买好了！");
        },"customer1").start();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程2：");
            goods3.buyThisGoods();
            System.out.println("顾客2买好了！");
        },"customer2").start();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程3：");
            goods3.buyThisGoods();
            System.out.println("顾客3买好了！");
        },"customer3").start();

    }
}

class Goods3{
    private String name = "商品1";
    /**
     * 库存
     */
    private int count = 0;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();


    public void buyThisGoods() {
        //加锁
        lock.lock();

        try {
            while(count==0){
                //库存为0，等待
                System.out.println("buyThisGoods等待");
                condition.await();
            }

            //库存不为0，商品库存减1
            count--;
            System.out.println("buyThisGoods: " + Thread.currentThread().getName() + "=>" + name + ":" + count);
            //通知其他线程
            condition.signalAll();
        }catch (Exception e){

        }finally {
            //解锁
            lock.unlock();
        }

    }

    public void addThisGoods(){


        lock.lock();
        count++;
        System.out.println("addThisGoods: " + Thread.currentThread().getName() + "=>" + name + ":" + count);
        //通知其他线程
        condition.signalAll();
        lock.unlock();
    }
}